<template>
    <div id="base_avatar_upload" class="clearfix">
       <!--上传文件按钮-->
       <div id="base_upload_btn_wrap">
           <div class="select_btn">
               <button id="base_upload_btn_select">select File</button>
               <input type="file" id="base_upload_file" @change="fileSelect($event)" accept="image/gif,image/jpeg,image/jpg,image/png,image/bmp"  />
           </div>
       </div>
       <!--上传图片容器-->
       <div id="base_upload_action_wrap">
           <div id="base_upload_img_wrap"></div>
           <div id="base_upload_preview" style=""></div>
           <div id="base_upload_btns">
                 <span class="icon icon-zoom-in" :style="{backgroundImage: 'url(' + icons + ')'}" @click="zoomIn"></span>
                 <span class="icon icon-zoom-out" :style="{backgroundImage: 'url(' + icons + ')'}"  @click="zoomOut"></span>
                 <span class="icon icon-rotate-left" :style="{backgroundImage: 'url(' + icons + ')'}" @click="rotateLeft"></span>
                 <span class="icon icon-rotate-right" :style="{backgroundImage: 'url(' + icons + ')'}"   @click="rotateRight"></span>
             </div>
       </div>
       <div class="imgCropper_button_group">
           <button v-touch-ripple class="cancel" type="button" @click="$emit('close')">Cancel</button>
           <button v-touch-ripple class="confirm"  type="button" @click="confirm">Confirm</button>
       </div>
    </div>
</template>

<script>
  import dModal from './Modal'
  require("../../assets/js/plugins/imgCropper/cropper.min.css");
  require("../../assets/js/plugins/imgCropper/cropper.min.js");
  import icons from '../../assets/js/plugins/imgCropper/icons.png'

  export default{
    components:{
      dModal
    },
    data:function(){
      return {
        $image:null,
        icons:icons
      }
    },
    props:{
      options:{
        url:"",
        formData:{},
        headers:{},
        fileName:"",
        params:{}
      }
    },
    methods:{
      fileCheck:function(str){
            debugger
        if (str == "") {
          layer.msg("请上传图片", {offset: 0,shift:6});
          return false;
        } else if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(str)) {
          layer.msg("图片类型必须是.gif,jpeg,jpg,png中的一种", {offset: 0,shift:6});
          str = "";
          return false;
        }
        return true;
      },
      fileSelect:function(e){
        var t = this;
        if(!t.fileCheck($(e.target).val())){
          $(e.target).val("");
          return false;
        }
        var reader = new FileReader();
        var oFile = $("#base_upload_file")[0].files[0];
        //图片文件文件不能大于2MB
        if(oFile.size > 2*1024*1024){
          layer.msg("文件大小不能超过2M", {offset: 0,shift:6});
          $(e.target).val("");
          return false;
        }
        reader.readAsDataURL(oFile);

        $("#base_upload_btn_wrap").hide(); //隐藏上传按钮
        $("#base_upload_action_wrap").show(); //显示裁剪容器
        reader.onload = function (e) {
          var url = e.target.result;
          var image=new Image();
          image.src=url;
          image.id = "base_img_crop";
          $("#base_upload_img_wrap").append(image);
          t.$image = $("#base_img_crop");

          t.$image.cropper({
            aspectRatio: 1 / 1,
            preview: '#base_upload_preview'
          });

        }
      },
      confirm:function(){
        var t  = this;
           //如果不支持html5文件接口则不处理
        if(typeof FileReader !== "function"){
          return false;
        }
        var $image = $("#base_img_crop");
        var oCanvas = $image.cropper('getCroppedCanvas', {
          width: 160,
          height: 160
        });

        if(typeof oCanvas.toDataURL == "function"){
          var data=oCanvas.toDataURL();
          // dataURL 的格式为 “data:image/png;base64,****”,逗号之前都是一些说明性的文字，我们只需要逗号之后的就行了
          data=data.split(',')[1];
          data=window.atob(data);
          var ia = new Uint8Array(data.length);
          for (var i = 0; i < data.length; i++) {
            ia[i] = data.charCodeAt(i);
          };

          // canvas.toDataURL 返回的默认格式就是 image/png
          var blob=new Blob([ia], {type:"image/png"});

          var formData = new FormData();
          formData.append(t.options.fileFormName, blob);
          if(!$.isEmptyObject(t.options.params)){
            for(var i in t.options.params){
              formData.append(i, t.options.params[i]);
            }
          }
          var oAjaxOpt = {
            url: t.options.url,
            method: "POST",
            data: formData,
            processData: false,
            contentType: false,
            beforeSend:function(){

            },
            success: function (data) {
              t.$emit('close');
              t.$emit('cropper-success',data)
            },
            error: function () {
              t.$emit('cropper-error')
            },
            complete:function(){

            }
          };
          if(t.options.headers && !$.isEmptyObject(t.options.headers)){
            oAjaxOpt.headers = t.options.headers;
          }
          $.ajax(oAjaxOpt);
        }
      },
      zoomIn:function(){
        this.$image.cropper("zoom", 0.1);
      },
      zoomOut:function(){
        this.$image.cropper("zoom", 0.1);
      },
      rotateLeft:function(){
        this.$image.cropper("rotate", -45);
      },
      rotateRight:function(){
        this.$image.cropper("rotate", 45);
      }
    }
  }
</script>
<style rel="stylesheet/scss" type="text/css" lang="scss" scoped>
  @import "../../assets/css/variable";


  /*头像上传并裁剪*/
  #base_avatar_upload{position: relative}
  #base_upload_btn_wrap{width: 544px; height: 428px; left: 5px; top: 5px;   border: 3px dashed #ccc;}
  #base_upload_btn_select{position: absolute; left: 50%; top: 50%; margin-left: -55px; margin-top: -17px;background: $activeColor;display: inline-block;       /* zoom and *display = ie7 hack for display:inline-block */      *display: inline;                        cursor: pointer;      text-align: center;      text-decoration: none;            -webkit-border-radius: 2px;      -moz-border-radius: 2px;      border-radius: 2px;      -webkit-transition-property: all;      transition-property: all;      -webkit-transition-duration: .3s;      transition-duration: .3s;      border: none;      -webkit-box-sizing: border-box;      -moz-box-sizing: border-box;      box-sizing: border-box;      font-family: "微软雅黑";      -webkit-appearance: none;width: 110px;height: 34px;line-height: 32px;color: #fff;font-size: 16px; padding: 0;}
  #base_upload_btn_select:hover{opacity: .8}
  #base_upload_file{position: absolute; left: 50%; top: 50%; margin-left: -45px; margin-top: -17px; opacity: 0; width: 90px; height: 35px;}
  #base_upload_btn_wrap .notsupport{position: absolute;left: 50%;top: 50%;line-height: 26px;font-size: 16px;width: 260px;height: 260px;margin-left: -152px;margin-top: -152px;background-color: #FFFFF1;opacity: 0.9;border: 1px dashed #929292;text-indent: 2em;padding: 20px;}
  #base_upload_action_wrap{width: 573px;height: 444px;overflow: hidden;position: relative;display: none;}
  #base_upload_img_wrap{width: 440px; height: 440px; border: 1px solid #ccc; position: absolute; left: 0; top: 0;}
  #base_upload_preview{position: absolute; left: 458px; width: 100px; height: 100px; border: 1px solid rgb(54, 163, 255); overflow: hidden; border-radius: 50%; top: 10px;}
  #base_upload_btns{position: absolute; width: 30px; height: 122px; top: 305px; background-color: #36A3FF; left: 469px; border-radius: 2px;}
  #base_upload_btns span.icon{/*background: url(icons.png);*/width: 20px;height: 20px;display: block;cursor: pointer;float: left;margin-left: 4px;margin-top: 6px;}
  #base_upload_btns span.icon-zoom-in{background-position: -59px 0;}
  #base_upload_btns span.icon-zoom-out{background-position: -89px 0;}
  #base_upload_btns span.icon-rotate-left{background-position: -119px 0;}
  #base_upload_btns span.icon-rotate-right{background-position: -150px 0;}


  /*图片自由裁剪*/
  #base_autoImgCut_upload{
      width: 900px;
      height: 560px;
  }
  #base_autoImgCut_btn_wrap{
      position: absolute;
      width: 880px;
      height: 540px;
      left: 5px;
      top: 5px;
      border: 3px dashed #ccc;
  }
  .imgCropper_button_group{
      margin-top: 20px;
      line-height: 40px;
      text-align: right;
      button{
          width: 80px;
          height: 30px;
          line-height: 30px;
          border-radius: 4px;
          border: 1px #DDDDDD solid;
          margin-right: 14px;
          cursor: pointer;
          &:hover{
              opacity: .7;
          }
          &.confirm{
              background-color: $activeColor;
              color: #fff;
              border-color:#fff ;
          }
          &.cancel{
              background-color: #fff;
              color: #333;
          }
      }
  }
</style>
